package 手写;

import java.util.concurrent.Semaphore;

//通过N个线程顺序循环打印从0至100
public class n个线程打印0到1002 {
    static int result = 0;

    public static void main(String[] args) throws InterruptedException {
        //假设有20个线程
        int n = 20;
        Thread[] threads = new Thread[n];
        Semaphore s = new Semaphore(100);
        for (int i = 0; i < n; i++) {
            final int index = i;
            threads[i] = new Thread(() -> {
                try {
                    while (true) {
                        s.acquire();
                        System.out.println("thread" + index + ": " + result++);
                        if (result > 100) {
                            System.exit(0);
                        }
                        s.release();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }

            });
            threads[i].start();
        }
    }
}
